// stores/projectStore.ts
import { defineStore } from 'pinia';
import { ref } from 'vue';
import {initialEdges, initialNodes} from '../components/data/initial-elements';
import {useServer} from '@/components/ts/useServer';
import {useUserStore} from '@/stores/userStore';
export const useProjectsStore = defineStore('projects', () => {
  // 存储所有打开的Project页面
  const projects = ref<{ id: string, name: string, content: {initialEdges:object,initialNodes:object}, loaded?: boolean}[]>([]);
     // 初始化方法
    const initializeProjects = async () => {
        const { post } = useServer();
        const userStore = useUserStore();

        try {
            const response = await post('fetchUserEditingProjects', { userID: userStore.currentUser });
            projects.value = response.projects.map((project: any) => ({
                id: project.projectID,
                name: project.projectName,
                content: project.content,
                loaded: true,
            }));
        } catch (error) {
            console.error('Failed to fetch projects:', error);
        }
    };

    // 更新项目名称的方法
    const updateProjectName = (projectId: string, newName: string) => {
        const project = projects.value.find(p => p.id === projectId);
        if (project) {
        project.name = newName;
        }
    };
    
    // 当前选中的Project
    const currentProjectId = ref<string | null>(null);
    // 添加一个新的Project
    const addProject = (name: string, content: {initialNodes:object, initialEdges:object }) => {
        const newProject = {
        id: `project-${projects.value.length + 1}`,
        name,
        content,
        };
        projects.value.push(newProject);
        currentProjectId.value = newProject.id; // 默认选中新建的Project
    };
    // 删除Project
    const removeProject = (id: string) => {
        projects.value = projects.value.filter(project => project.id !== id);
        if (currentProjectId.value === id) {
        currentProjectId.value = null; // 清除当前Project的选中状态
        }
    };

    // 设置当前选中的Project
    const setCurrentProject = (id: string) => {
        console.log('setCurrentProject', id);
        currentProjectId.value = id;
    };

    let timer: any | null = null;
    let forceTimer: any | null = null;
    let forcing:boolean = false;
    const updateInterval = 2000; // 3秒内不被调用则更新
    const forceUpdateInterval = 10000; // 每10秒强制更新一次
    const {post,postWithCallback}=useServer();
    const userStore=useUserStore();
    // 模拟网络更新函数
    const networkUpdate = (projectID:string) => {
        let pro = projects.value.find(p => p.id === projectID)
        postWithCallback('saveUserProject',{userID:userStore.currentUser, projectID:projectID, content: {projectName: pro?.name, content: pro?.content} },(res)=>{
            if(res.success){
                console.log('Saving Success')
            }
            else{
                console.log('Saving Failed')
            }
        })
        
    };
    // 更新Project内容
    const updateProjectContent = (id: string, content: {initialNodes:object, initialEdges:object}, atOnce:boolean=false) => {
        const project = projects.value.find(p => p.id === id);
        if (project) {
            project.content = content;
        }
        else return

        if (atOnce){
            if (timer) {
                clearTimeout(timer);
                timer = null;
            }
            if (forceTimer) {
                clearTimeout(forceTimer);
                forceTimer = null;
            }
            networkUpdate(id);
            forcing = false;
            return
        }
        // 缓冲网络更新
        if (timer) {
            clearTimeout(timer);
        }
        // 设置新的定时器
        timer = setTimeout(() => {
            networkUpdate(id);
        }, updateInterval);
        // 每10秒强制触发一次网络更新
        if(forcing){
            return;
        }
        forceTimer = setTimeout(() => {
            networkUpdate(id);
            forcing = false;
        }, forceUpdateInterval);
        forcing = true;
    };

    // 复制一个Project
    const copyProject = (id: string) => {
        const projectToCopy = projects.value.find(p => p.id === id);
        if (projectToCopy) {
            addProject(`${projectToCopy.name} (Copy)`, projectToCopy.content);
        }
    };

    return {
        projects,
        currentProjectId,
        addProject,
        removeProject,
        setCurrentProject,
        updateProjectContent,
        copyProject,
        updateProjectName,
        initializeProjects,
    };
});
